const path = require("path");
const fse = require("fs-extra");
const { basename } = require("path");
const JSZip = require("jszip");

const COMMAND_FOLDER = path.dirname(__filename);
const CONFIG_FILE = path.join(COMMAND_FOLDER, "config.json");
let PROJECT = path.dirname(COMMAND_FOLDER).replace("/packages", "");

async function loadJsonData(path) {
    if (!fse.existsSync(path)) {
        await fse.writeJson(path, {});
    }

    return fse.readJson(path);
}

function handleJsonData(data) {
    const file_list = data.files;
    const handled_list = [];
    for (const file of file_list) {
        const filePath = path.join(PROJECT, file);
        handled_list.push(filePath);
    }
    return handled_list;
}

/**
 *
 * @param files {string[]} 压缩文件数组
 * @param out
 * @returns {Promise<void>}
 */
async function packageFiles(files, out) {
    let errorsCount = 0;
    let successCount = 0;
    const zip = new JSZip();
    for (const file of files) {
        if (!fse.existsSync(file)) {
            // Editor.warn("file:",file);
            errorsCount++;
        } else {
            const fileData = await fse.readFile(file);
            zip.file(basename(file), fileData);
            successCount++;
        }
    }
    const zipData = await zip.generateAsync({ type: "nodebuffer" });
    await fse.writeFile(out, zipData);

    if (errorsCount > 0) {
        // Editor.log(`打包失败${errorsCount}个文件`);
    }
    if (successCount > 0) {
        // Editor.log(`打包成功${successCount}个文件`);
    }
}

async function zipBuild(isWin) {
    if (isWin) {
        PROJECT = PROJECT.replace("\\packages", "");
    }
    Editor.log("准备开始压缩文件",PROJECT);
    const data = await loadJsonData(CONFIG_FILE);
    const handleList = data;
    for (const handleData of handleList) {
        const fileList = handleJsonData(handleData),output = path.join(PROJECT, handleData.output);
        if(!fse.pathExistsSync(output)){
            fse.ensureFileSync(output);
        }
        await packageFiles(fileList, output);
    }
}

module.exports = zipBuild;

// main().catch(error => console.error(error));
